import requestAPI from '../../utils/requestApi';

Page({
  data: {
    swiperImages: [], // 这里假设有多张图片路径，可以按实际情况修改和添加更多图片路径哦
    ThemeList: {
      title: '',
      article: '',
      time: '',
      longitude: '',
      latitude: '',
      distance: '',
      address: '',
      isFavorite: false // 假设初始状态不是收藏的
    },
    historyList: [] // 存储历史浏览记录
  },

  fetchActivityDetail: function (id) {
    const that = this;
    const userKey = wx.getStorageSync('userKey');
    const relativeUrl = '/travel/actives/detail';
    console.log(relativeUrl)
    const url = `?userKey=${userKey}&id=${id}`; // 将userKey和id拼接在URL中
    requestAPI.get(relativeUrl + url).then(res => {
      if (res) {
        const activityDetails = res.data.activityDetails;
        this.setData({
          swiperImages: res.data.swiperImages,
          ThemeList: {
            id: res.data.ThemeList.id,
            title: res.data.ThemeList.title,
            article: res.data.ThemeList.articleCon,
            time: res.data.ThemeList.times,
            longitude: res.data.ThemeList.longitude,
            latitude: res.data.ThemeList.latitude,
            distance: '',
            address: res.data.ThemeList.address,
            isFavorite: res.data.ThemeList.isFavorite
          }
        });
          // 调用添加历史记录的函数
          const name = res.data.ThemeList.title;
          const images = res.data.swiperImages.map(img => img);
          const type = 'active';
          const itemId = id; 
          that.addHistoryRecord(id, name, images, userKey, type, itemId);
        }
      }).catch((err) => {
        console.error('获取活动详细信息失败', err);
      });
    },

  previewImage: function(e) {
    const currentSrc = e.currentTarget.dataset.imgurl; // 获取当前点击的图片的src
    const images = this.data.swiperImages; // 假设所有图片的路径都存储在swiperImages数组中

    // 调用预览大图API
    wx.previewImage({
      current: currentSrc, // 当前显示图片的链接，根据点击的图片设置
      urls: images // 需要预览的图片链接列表，这里假设swiperImages存储的是图片路径数组
    });
  },

  // 导航定位
  mapClick: function () {
    const { latitude, longitude, title, address } = this.data.ThemeList;
    if (latitude && longitude) {
      // 如果有经纬度，跳转到具体位置
      wx.openLocation({
        latitude: parseFloat(latitude),
        longitude: parseFloat(longitude),
        name: title,
        address: address,
      });
    } else {
      // 如果没有经纬度，跳转到默认位置
      wx.openLocation({
        latitude: 39.9042, // 默认北京市中心
        longitude: 116.4074,
        name: '默认位置',
        address: '北京市中心',
      });
    }
  },

  // 切换收藏状态并发送请求更新服务器端的收藏状态
  toggleFavorite: function(event) {
    const that = this;
    const userKey = wx.getStorageSync('userKey'); // 从本地存储获取userKey
    const themeList = this.data.ThemeList;
    console.log(this.data.ThemeList);
    const isFavorite = !themeList.isFavorite;

    if (!userKey) {
      wx.showToast({
        title: '请先登录',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    // 更新本地收藏状态
    themeList.isFavorite = isFavorite;
    this.setData({
      ThemeList: themeList
    });
    // 显示提示
    wx.showToast({
      title: isFavorite ? '收藏成功' : '取消收藏',
      icon: isFavorite ? 'success' : 'none',
      duration: 2000
    });

    // 根据收藏状态决定发送请求的URL
    const relativeUrl = isFavorite ? '/travel/favorite/add' : '/travel/favorite/remove';
    const data = {
      userKey: userKey,
      type: 'active', // 假设收藏的是活动
      itemId: themeList.id // 假设每个活动有一个唯一的id
    };
    console.log(data)
    // 发送POST请求更新收藏状态
    requestAPI.post(relativeUrl, data, { openid: userKey }).then(res => {
      console.log(res);
      if (res.code === 200) {
        console.log('收藏状态更新成功');
        // 通知收藏页面刷新数据
        wx.setStorageSync('refreshFavorites', true);
      } else {
        wx.showToast({
          title: '收藏状态更新失败，请重试',
          icon: 'none',
          duration: 2000
        });
      }
    }).catch(error => {
      console.error('更新收藏状态失败:', error);
      wx.showToast({
        title: '收藏状态更新失败',
        icon: 'none',
        duration: 2000
      });
    });
  },

  // 添加历史记录
  addHistoryRecord: function(id, name, images, userKey, type, itemId) {
    const postData = {
      userKey: userKey,
      name: name,
      images: images[0],
      type: type,
      itemId: itemId
    };
  
    // 使用requestAPI.post发送POST请求
    requestAPI.post('/travel/history/add', postData, { openid: userKey }).then(response => {
      if (response.code === 200) {
        console.log('历史记录添加成功');
      } else {
        console.error('历史记录添加失败:', response.message);
      }
    }).catch(error => {
      console.error('请求失败:', error);
    });
  },

  onLoad: function(options) {
    const activityId = options.id;
    this.fetchActivityDetail(activityId);
  }
});